package com.ruoyi.hr.common.aspect;

import com.ruoyi.hr.common.annotation.HrLog;
import com.ruoyi.hr.common.utils.BaseThreadLocal;
import com.ruoyi.hr.domain.HrOperateLog;
import com.ruoyi.hr.domain.dto.HrLogAddDto;
import com.ruoyi.hr.service.IHrOperateLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Aspect
@Component
public class HrLogAspect {

	@Autowired
	private IHrOperateLogService hrOperateLogService;


	@Before("@annotation(hrLog)")
	public void logBefore(JoinPoint joinPoint, HrLog hrLog) throws Throwable {
		HrLogAddDto hrLogAddDto = new HrLogAddDto();
		// 直接访问hrLog注解的operationType属性
		String operationType = hrLog.operationType();
		// 打印操作类型
		hrLogAddDto.setType(operationType);
		hrLogAddDto.setOperator(BaseThreadLocal.getUserName());
		hrLogAddDto.setTime(new Date());
		hrLogAddDto.setContent("");
		hrLogAddDto.setAdvice("");
		hrLogAddDto.setSupplement("");
		BaseThreadLocal.setHrLog(hrLogAddDto);
	}

	/**
	 * 切面方法, 后置通知, 然后的话就是, 加了这个注解的方法里面必须先组织好一个HrOperationLog 的对象并保存到threadLcoal里面, 这里再做日志记录
	 * 这样比较灵活
	 * @param joinPoint
	 * @param hrLog
	 * @throws Throwable
	 */
	@After("@annotation(hrLog)")
	public void logAfter(JoinPoint joinPoint, HrLog hrLog) throws Throwable {
		// 打印操作类型
		HrLogAddDto hrLogAddDto = BaseThreadLocal.getHrLog();
		// 得到所有简历Id
		List<Long> resumeIds = hrLogAddDto.getResumeIds();

		if(resumeIds != null && resumeIds.size() > 0){
			List<HrOperateLog> collect = resumeIds.stream().map(item -> {
				HrOperateLog hrOperateLog = new HrOperateLog();
				BeanUtils.copyProperties(hrLogAddDto, hrOperateLog);
				hrOperateLog.setResumeId(item);
				return hrOperateLog;
			}).collect(Collectors.toList());

			// 对collection进行插入操作
			hrOperateLogService.insertHrOperateLogBatch(collect);
		}
		BaseThreadLocal.removeHrLog();
	}


}
